package br.senai.sc.web.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.senai.sc.controller.crud.FotoCRUD;
import br.senai.sc.model.Anexo;
import br.senai.sc.model.Foto;

@WebServlet("/image/*")
public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Inject
	private FotoCRUD fotoCRUD;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String imageId = String.valueOf(request.getPathInfo().substring(1)); // Gets
																				// string
																				// that
																				// goes
																				// after
																				// "/images/".
		Foto foto = fotoCRUD.find(Integer.parseInt(imageId)); // Get Image from
																// DB.
		Anexo anexo = foto.getAnexo();

		response.setHeader("Content-Type", anexo.getMimeType());
		response.setHeader("Content-Disposition",
				"inline; filename=\"" + anexo.getNome() + "\"");

		BufferedInputStream input = null;
		BufferedOutputStream output = null;

		try {

			ByteArrayInputStream in = new ByteArrayInputStream(
					anexo.getArquivo());
			input = new BufferedInputStream(in);
			output = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[8192];
			for (int length = 0; (length = input.read(buffer)) > 0;) {
				output.write(buffer, 0, length);
			}
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException logOrIgnore) {
				}
			}
			if (input != null) {
				try {
					input.close();
				} catch (IOException logOrIgnore) {
				}
			}
		}
	}
}
